apiready = function() {
    var photoBrowser = api.require('photoBrowser');
    var iOSDialog = api.require('iOSDialog');
    var app = new Vue({
        el:'#app',
        data() {
            return {
				iosTest:false,
                device:[
                    {id:1,title:'安卓',img:'../../../image/push/android.png',
                        isSelect: true,value: 'Android'
                    },
                    {id:2,title:'苹果',img:'../../../image/push/apple.png',
                        isSelect: true,value: 'iOS'
                    },
                ],
                bid: '',
                isShowHighSet: false,
                // 模式 major 自定义 simple 简单  system 系统
                mode: 'simple',
                tpType: {
                    title: '',
                    name: ''
                },
                // 主题信息
                tpLink: {
                    id: '',
                    title: '',
                    price: '',
                    num: ''
                },
                targets:[],
                commands:[],
                // 任务步骤
                taskSteps: [],
                // 简易模式
                simpleObj: {
                    // 任务描述
                    taskSpec: '',
                    // 简单流程示例图集合
                    simpleFlowImgs: [],
                    // 简单流程任务参数
                    target: {
                        id: '',
                        type: '链接',
                        value: '',
                        content: ''
                    },
                    // 验收示例图集合
                    simpleCheckImgs: [],
                    // 收集文字集合
                    simpleCotTexs: '',
                },
                highSet: {
                    autoReleaseTime: '',
                    releaseAllowEdit: 1,
                    autoPassTime: '',
                    passAllowEdit: 1,
                    autoCloseTime: '',
                    closeAllowEdit: 1,
                    // hour 小时  day 天
                    closeTimeType: 'hour',
                    devices: ["Android","iOS"],
                    devicesAllowEdit: 1
                },
                hasTemplate: false,
                // 当前使用模版
                curTemplateLink: null,
                isPageLoading: true
            }
        },
        created() {
            this.getOpercommandsApi();
            this.parseParam();
        },
        mounted() {
            $.initJs(this);
        },
        computed: {
            totalSpendPrice() {
                var userInput = this.tpLink;
                var price = userInput.price || 0;
                var num = userInput.num || 0;
                return Number(price * num).toFixed(2);
            },
            isShowAddHandle() {
                return this.mode === 'system' ? false : true;
            },
        },
        methods:{
            init: function() {
                this.bid = this.createId();
                if (this.mode === 'system') {
                    this.getSystemTemplateAPI();
                }else{
                    this.getTemplateApi();
                }
            },
                /**
             *  生产bid
             */
            createId() {
                var bid = $.createBid();
                return bid;
            },
            createBidPrefix(fileType) {
                return $.createUploadPrefix({
                    fileType: fileType
                });
            },
            getPageParam: function() {
                return api.pageParam;
            },
            parseParam: function() {
                let params = this.getPageParam().data;
                this.mode = params.mode;
                this.tpLink = {
                    id: params.tpid,
                    title: params.titles,
                    price: params.price,
                    num: params.num
                };
                this.tpType = {
                    title: params.typeTitle,
                    name: params.typeName
                }
            },
            selectShowImg: function (uri) {
                if (this.getLinkType(uri) === 'img') {
                    return uri;
                }
                return '../../../image/push/video2.png';
            },
            handleShowHighSet: function() {
                this.isShowHighSet = !this.isShowHighSet;
            },
            getLinkType(url) {
                return utils.isFile(url);
            },
            simpleParSelect: function () {
                var targets = this.targets;
                var _self = this;
                var assignFn = function (targetIndex) {
                    var useTarget = targets[targetIndex];
                    _self.simpleObj.target = {
                        id: useTarget.id,
                        type: useTarget.name,
                        value: '',
                        content: ''
                    }
                }
                this.handleBtnLinks(assignFn);
            },
            majorParSelect: function (stepIndex,ctIndex) {
                if (this.mode === 'system') {
                    return;
                }
                var targets = this.targets;
                var commands = this.commands;
                var _self = this;
                var taskSteps = utils.simpleCopyObj(this.taskSteps);
                var curStep = taskSteps[stepIndex];
                var curCt = curStep[ctIndex];
                var assignFn = function (targetIndex) {
                    var useTarget = targets[targetIndex];
                    var content = [];
                    for(var i=0;i<useTarget.operations.length;i++) {
                        var curOpera = useTarget.operations[i];
                        if (commands[curOpera]) {
                            content.push(commands[curOpera].name);
                        }
                    }
                    curCt.target.type = useTarget.name;
                    curCt.target.content = content;
                    _self.$set(_self.taskSteps,stepIndex,curStep);
                }
                this.handleBtnLinks(assignFn);
            },
            handleBtnLinks(callBack) {
                var targets = this.targets;
                var listName = [];
                for(var i=0;i<targets.length;i++ ) {
                    listName.push(targets[i].name);
                }
                var param = {title:"请选择操作",items: listName};
                iOSDialog.actionSheetDialog(param,function(ret, err){
                    if (ret.index && ret.index > 0) {
                        callBack(ret.index - 1);
                    }
                });
            },
            simpleUploadFlowsImg: function() {
                var _self = this;
                var handleFlowsResImg = function (url,imgId) {
                    _self.simpleObj.simpleFlowImgs.push({
                        uri: url,
                        fid: imgId
                    })
                }
                this.uploadImg(handleFlowsResImg);
            },
            deleteSimpleFlowsImg: function (flowIndex) {
                this.simpleObj.simpleFlowImgs.splice(flowIndex,1);
            },
            simpleUploadCheckImg: function () {
                var _self = this;
				$.alert("添加验证图，需要自己先上传一张示例图哦~",function(){
					var handleCheckResImg = function (url,imgId) {
					    _self.simpleObj.simpleCheckImgs.push({
					        uri: url,
					        fid: imgId
					    })
					}
					_self.uploadImg(handleCheckResImg);
				});
            },
            deleteSimpleCheckImg: function (checkIndex) {
                this.simpleObj.simpleCheckImgs.splice(checkIndex,1);
            },
            handleFileNext: function (fileUrl) {
                if(fileUrl) {
                    var type = utils.isFile(fileUrl);
                    if (type && type === 'video') {
                        api.openVideo({
                            　　url: fileUrl
                        });
                    }else{
                        this.openFile(fileUrl);
                    }
                }
            },
               // 图片预览
            openFile: function(fileUrl) {
                photoBrowser.open({
                    images: [fileUrl],
                    bgColor: '#000'
                }, function(photoRes, err) {
                    if(photoRes && photoRes.eventType=="click"){
                        photoBrowser.close();
                    }else if(photoRes && photoRes.eventType == 'longPress'){
                        var param = {title:"提示",items:["保存到系统相册"]};
                        iOSDialog.actionSheetDialog(param,function(ret, err){
                            if(ret.index == 1){
                                $.saveMediaToAlbum(fileUrl, function(){
                                    $.toast('图片已保存到系统相册');
                                });
                            }
                        });
                    }
                });
            },
            uploadImg: function(callBack) {
                var _self = this;
                api.getPicture({
                    sourceType: 'library',
                    encodingType: 'jpg',
                    mediaValue: 'pic',
                    destinationType: 'url',
                    quality: 80
                }, function(ret, err){
                    if (ret.data) {
                        var img_pic1 = ret.data;
                        _self.uploadImgApi(img_pic1,callBack);
                    }
                });
            },
            uploadImgApi: function (imgUrl,callBack) {
                var _self = this;
                var imgType = this.getLinkType(imgUrl);
                var filenameArr = imgUrl.split('/');
                var bid = 'Task' + '-' + this.bid;
                $.comRequest('post','/file/upload',{
                    values: {
                        bid: bid,
                        filename: filenameArr[filenameArr.length - 1],
                        type: imgType === 'video' ? 'video' : 'jpg',
                    },
                    files: {
                        file: imgUrl,
                    }
                },function(res){
                    var data = res.data;
                    callBack(data.url,data.id);
                },function(ero){
                    $.toast(ero.message)
                },true)
            },
            // 获取任务步骤可操作项
            getOpercommandsApi: function() {
                var _self = this;
                $.comRequest('get','/task/step/all_opercommands',{},function(res){
                    _self.targets = res.data.targets;
                    _self.commands = res.data.commands;
					_self.init();
                },function(ero){
					_self.init();
                    $.toast(ero.message);
                });
            },
            /**
             *  获取默认可操作按钮信息
             *
             */
            getDefaulHtBtnLink() {
                let targets = JSON.parse(JSON.stringify(this.targets));
                let defaultHbtn = targets[0] || {name: '未定义'};
                let usable = '';
                if (targets.length > 0) {
                    let commands = JSON.parse(JSON.stringify(this.commands));
                    if (Array.isArray(defaultHbtn.operations)) {
                            // 取两数组交集
                            usable = [];
                            //curHbtn.operations.filter(hbtn=> commands.hasOwnProperty(hbtn))
                            defaultHbtn.operations.forEach((hbtn)=>{
                                if(commands.hasOwnProperty(hbtn)){
                                    usable.push(commands[hbtn].name);
                                }
                            });
                    }
                }
                return {
                    name: defaultHbtn.name,
                    usable
                }
            },
            addTaskStep: function () {
                this.taskSteps.push([]);
            },
            /**
             *  删除步骤中内容模板
             * @param { String } stepIndex 步骤索引
             * @param { String } ctIndex  内容索引
             */
            deleteStepContent: function(stepIndex,ctIndex){
                var taskSteps = utils.simpleCopyObj(this.taskSteps);
                var curstep = taskSteps[stepIndex];
                curstep.splice(ctIndex,1);
                this.taskSteps = taskSteps;
            },
            /**
             *  删除步骤-内容下的文件
             * @param { String } stepIndex 步骤索引
             * @param { String } ctIndex  内容索引
             * @param { String } fileIndex  文件索引
             */
            deleteStepFile: function (stepIndex,ctIndex,fileIndex) {
                var taskSteps = utils.simpleCopyObj(this.taskSteps);
                var curStep = taskSteps[stepIndex];
                var curCts = curStep[ctIndex];
                curCts.splice(fileIndex,1);
                this.$set(this.taskSteps,stepIndex,curStep);
            },
            /**
             *  任务步骤操作内容模块
             * @param { String } stepIndex 步骤索引
             */
            selectTaskStepContent: function (stepIndex) {
                var _self = this;
                var taskSteps = utils.simpleCopyObj(this.taskSteps);
                var curStep = taskSteps[stepIndex];
                var slotOBj = {
                    0: function () {
                        curStep.push({
                            type:'Description',
                            value:''
                        });
                        _self.$set(_self.taskSteps,stepIndex,curStep);
                    },
                    1: function () {
                        var margeImgsFn = function (imgUrl,imgId) {
                            if (Array.isArray(curStep[curStep.length -1 ])) {
                                curStep[curStep.length -1 ].push({
                                    type:"Gallery",
                                    uri: imgUrl,
                                    fid: imgId
                                });
                            }else{
                                curStep.push([{
                                    type:"Gallery",
                                    uri: imgUrl,
                                    fid: imgId
                                }]);
                            }
                            _self.$set(_self.taskSteps,stepIndex,curStep);
                        };
                        _self.uploadImg(margeImgsFn);
                    },
                    2: function () {
                        var defaultHbtn= _self.getDefaulHtBtnLink();
                        curStep.push({
                                type: 'Operable',
                                target: {
                                    type: defaultHbtn.name,
                                    value: '',
                                    content: defaultHbtn.usable
                                }
                        });
                        _self.$set(_self.taskSteps,stepIndex,curStep);
                    },
                    3: function () {
                        curStep.push({
                            type:'CollectTextInfo',
                            placeholder: '',
                            value: ''

                        });
                        _self.$set(_self.taskSteps,stepIndex,curStep);
                    },
                    4: function () {
                        if (Array.isArray(curStep[curStep.length -1 ])){
                            curStep[curStep.length -1 ].push({
                                type:"CollectGallery",
                                uri: '',
                            });
                        }else{
                            curStep.push([{
                                type:"CollectGallery",
                                uri: '',
                            }])
                        }
                        _self.$set(_self.taskSteps,stepIndex,curStep);
                    },
                    5: function () {
                        _self.taskSteps.splice(stepIndex, 1);
                    },
                    6: function () {
                        var tempStep = taskSteps[stepIndex - 1];
                        taskSteps[stepIndex] = tempStep;
                        taskSteps[stepIndex - 1] = curStep;
                        _self.taskSteps = taskSteps;
                    },
                    7: function () {
                        var tempStep = taskSteps[stepIndex + 1];
                        taskSteps[stepIndex] = tempStep;
                        taskSteps[stepIndex + 1] = curStep;
                        _self.taskSteps = taskSteps;
                    }
                };
                var selcetCallBack = function (selectIndex) {
                    slotOBj[selectIndex]();
                }
                this.handleStepContent(selcetCallBack);
            },
            handleStepContent(callBack) {
                var baseSelect= [
                    '添加介绍文字',
                    '添加示例图/视频',
                    '添加可操作的按钮',
                    '收集用户文字',
                    '收集用户图片',
                    '删除本列',
                ];
                // 步骤大于1
                if (this.taskSteps.length > 1) {
                    baseSelect = baseSelect.concat(['上移','下移']);
                }
                var param = {title:"请选择操作",items: baseSelect};
                iOSDialog.actionSheetDialog(param,function(ret, err){
                    if (ret.index && ret.index > 0) {
                        callBack(ret.index - 1);
                    }
                });
            },
            // 选择设备
            selectdDevice(deIndex){
                if (this.highSet.devicesAllowEdit != 1) {
                    $.toast('您只需要填写绿色框信息即可。');
                    return;
                }
                let diList = JSON.parse(JSON.stringify(this.device));
                let curDi = JSON.parse(JSON.stringify(diList[deIndex]));
                let changeState = !curDi.isSelect;
                curDi.isSelect = changeState;
                diList[deIndex] = curDi;
                let newArr = [];
                // 根据是否选择筛选出操作平台
                diList.forEach(diItem => {
                    if (diItem.isSelect) {
                        newArr.push(diItem.value);
                    }
                });
                // 只剩下一个时候
                if (newArr.length <=0) {
                    diList[deIndex].isSelect = !changeState;
                }else{
                    this.limited_os = newArr;
                }
                this.device = diList;
                this.cachePageData();
            },
            selectCloseTime() {
                var _self = this;
                var param = {title:"请选择",items: [
                    '小时',
                    '天'
                ]};
                iOSDialog.actionSheetDialog(param,function(ret, err){
                    if (ret.index && ret.index > 0) {
                          // hour 小时  day 天
                        _self.highSet.closeTimeType = ret.index == 1 ? 'hour' : 'day' ;
                    }
                });
            },
            parFiexdHint: function(type){
                if(this.mode !== 'system') {
                    return;
                }
                if (type) {
                    $.toast('您只需要填写绿色框信息即可。');
                }
            },
            comCheckSteps: function () {
                let mode = this.mode;
                // 模式 major 自定义 simple 简单  system 系统
                if ( mode === 'simple' ) {
                    this.taskSteps =  this.parseSimpleStep();
                    if (!this.checkSimpleTaskSteps()) {
                        return false;
                    }
                }
                if (!this.checkTaskSteps()) {
                    return false;
                }
                return true;
            },
            publishWill: function () {
                if (!this.comCheckSteps()) {
                    return;
                }
                this.publishDid();
            },
            // id: '',
            // title: '',
            // price: '',
            // num: ''
            publishDid: function () {
                var resPar = this.parsePublishPar();
                var isCollectInfo = false;
				var custom_steps= JSON.stringify(resPar.custom_steps);
				if(custom_steps.indexOf("CollectTextInfo")!=-1 || custom_steps.indexOf("CollectGallery")!=-1){
					isCollectInfo = true;
				}
                /*for(let stepIndex=0; stepIndex<resPar.custom_steps.length; stepIndex++){
                    let curStep = resPar.custom_steps[stepIndex];
                    for(let ctIndex =0; ctIndex<curStep.length; ctIndex++){
                        let curCt = curStep[ctIndex];
                        if (curCt.type === 'CollectTextInfo' || curCt.type === 'CollectGallery') {
                            isCollectInfo = true;
                            break;
                        }
                    }
                }*/
                var publishApi = function () {
                    $.comRequest('post','/task/publish',resPar,function(res){
                        $.alert(res.message,function () {
							api.sendEvent({name: 'updateMyIndexPage'});
                            api.closeToWin({name:'root'});
                        });
                    },function(ero){
                        $.toast(ero.message);
                    },true);
                }
                if (isCollectInfo) {
                    publishApi();
                }else{
                    $.confirm({
                        title: '提示',
                        msg: '您暂未收集用户信息，可能会导致无法验证用户任务完成情况！是否确认？',
                        buttons: ['取消','确定'],
                        success:function(){
                            publishApi();
                        }
                    });
                }
            },
            parsePublishPar: function () {
                var tpLink = this.tpLink;
                var taskSteps = this.taskSteps;
                var highSet = this.parseHighSet();
                var resPar = {
                    tp_id: tpLink.id,
                    title: tpLink.title,
                    amount: tpLink.price * CONFIG.PRICE_RADIO,
                    total_accepts: tpLink.num,
                    limited_time: highSet.autoReleaseTime, // autoReleaseTime
                    limited_time_approve: highSet.autoPassTime, // autoPassTime
                    deadline_time: highSet.autoCloseTime, // autoCloseTime
                    limited_os: highSet.devices, // devices
                    bid: CONFIG.constants.TASK + '-'+this.bid,
                    custom_steps: taskSteps
                };
                return resPar;
            },
            parseHighSet: function () {
                var highSet = this.highSet;
                var deviceList = this.device;
                var devices = [];
                for(var i=0;i<deviceList.length;i++){
                    var curDevice = deviceList[i];
                    if (curDevice.isSelect) {
                        devices.push(curDevice.value);
                    }
                }
                if (highSet.closeTimeType === 'day') {
                    highSet.autoCloseTime = highSet.autoCloseTime * 24;
                }
                return {
                    autoReleaseTime: highSet.autoReleaseTime,
                    autoPassTime: highSet.autoPassTime,
                    autoCloseTime: highSet.autoCloseTime,
                    devices: devices
                }
            },
            checkSimpleTaskSteps: function () {
                var taskSteps = this.taskSteps;
                if (taskSteps.length <= 0) {
                    $.toast('任务描述不能为空!');
                    return false;
                }
                return true;
            },
            checkTaskSteps: function  () {
                var taskSteps = this.taskSteps;
                if(taskSteps.length <= 0) {
                    $.toast('任务步骤不能为空!')
                    return false;
                }
                for(let stepIndex=0; stepIndex<taskSteps.length; stepIndex++){
                    let curStep = taskSteps[stepIndex];
                    if (curStep.length <=0) {
                        $.toast('第'+ (stepIndex+1) +'步需要添加内容');
                        return false;
                    }
                    for(let ctIndex =0; ctIndex<curStep.length; ctIndex++){
                        let curCt = curStep[ctIndex];
                        if (Array.isArray(curCt)){
                            continue;
                        }
                        let baseSpec = '第' + (stepIndex+1) + '步中第'+ (ctIndex+1) +'个模块';
                        if (curCt.type === "Description" && utils.isNullStr(curCt.value)) {
                            $.toast(baseSpec + '需要填写介绍文字!');
                            return false;
                        }
                        if (curCt.type === "Operable" && utils.isNullStr(curCt.target.value)) {
                            $.toast(baseSpec + '需要填写内容!');
                            return false;
                        }
                        if (curCt.type === "CollectTextInfo" && utils.isNullStr(curCt.placeholder)) {
                            $.toast(baseSpec + '需要填写收集信息!');
                            return false;
                        }
                    }
                }
                return true;
            },
            /**
             *  解析任务步骤
             */
            parseSimpleStep: function() {
                var simpleObj = this.simpleObj;
                var taskSpec = simpleObj.taskSpec;
                var simpleFlowImgs = simpleObj.simpleFlowImgs;
                var target = simpleObj.target;
                var simpleCheckImgs = simpleObj.simpleCheckImgs;
                var simpleCotTexs = simpleObj.simpleCotTexs;
                var baseStep = [[],[]];
                if (!utils.isNullStr(taskSpec)) {
                    baseStep[0].push(
                        {
                            type:'Description',
                            value: taskSpec
                        }
                    )
                }
                if (simpleFlowImgs.length > 0) {
                    var simpleArr = [];
                    for (var flowIndex=0;flowIndex<simpleFlowImgs.length;flowIndex++){
                        var curFlow = simpleFlowImgs[flowIndex];
                        curFlow.type = 'Gallery';
                        simpleArr.push(curFlow);
                    }
                    baseStep[0].push(simpleArr);
                }
                if (!utils.isNullStr(target.value)) {
                    baseStep[0].push({
                        type: 'Operable',
                        target: target
                    });
                }
                if (!utils.isNullStr(simpleCotTexs)) {
                    var cltLsit = simpleCotTexs.split('\n');
                    for (let i=0;i<cltLsit.length;i++){
                        if (utils.isNullStr(cltLsit[i])) {
                            continue;
                        }
                        baseStep[1].push({
                            type:'CollectTextInfo',
                            placeholder: cltLsit[i],
                            value: ''
                        });
                    }
                }
                if (simpleCheckImgs.length > 0) {
                    var checkArr = [];
                    for(var checkIndex=0;checkIndex<simpleCheckImgs.length;checkIndex++) {
                        var curCheck = simpleCheckImgs[checkIndex];
                        curCheck.type = 'Gallery';
                        checkArr.push(curCheck);
                        checkArr.push({
                            type: "CollectGallery",
                            uri: ""
                        });
                    }
                    baseStep[1].push(checkArr);
                }
                if (baseStep[0].length <= 0) {
                    return [];
                }
                if (baseStep[1].length <=0) {
                    baseStep.splice(1,1);
                }
                return baseStep;
            },
            getSystemTemplateAPI: function() {
                let _self = this;
                var initSteps = function  (steps) {
                    var taskSteps = steps;
                    var targets = _self.targets;
                    var commands = _self.commands;
                    for(let stepIndex=0; stepIndex<taskSteps.length; stepIndex++){
                        let curStep = taskSteps[stepIndex];
                        for(let ctIndex =0; ctIndex<curStep.length; ctIndex++){
                            let curCt = curStep[ctIndex];
                            if (Array.isArray(curCt)){
                                continue;
                            }
                            curCt.canInput = true;
                            if (curCt.type === "Description" && !utils.isNullStr(curCt.value)) {
                                curCt.canInput = false;
                            }
                            if (curCt.type === "Operable") {
                                var target = {
                                    operations: []
                                };
                                var content = [];
                                for(var targetIndex=0;targetIndex<targets.length;targetIndex++) {
                                    var curTarget = targets[targetIndex];
                                    if (curTarget.name === curCt.target.type) {
                                        target = curTarget;
                                        break;
                                    }
                                }
                                for (var operIndex=0;operIndex<target.operations.length;operIndex++) {
                                    var curOper = target.operations[operIndex];
                                    if(commands[curOper]) {
                                        content.push(commands[curOper].name)
                                    }
                                }
                                curCt.target.content = content;
                                if (!utils.isNullStr(curCt.target.value)) {
                                    curCt.canInput = false;
                                }
                            }
                            if (curCt.type === "CollectTextInfo" && !utils.isNullStr(curCt.placeholder)) {
                                curCt.canInput = false;
                            }
                        }
                        taskSteps[stepIndex] = curStep;
                    }
                    return taskSteps;
                }
                var initHighSet = function (template) {
                    var device = utils.simpleCopyObj(_self.device);
                    var devices = [];
                    if (template.limited_os) {
                        for (var i=0;i<template.limited_os.systems;i++) {
                            var curDevice = template.limited_os.systems[i];
                            for (var j=0;j<device.length;j++) {
                                device[j].isSelect = false;
                                if (device[j].value === curDevice) {
                                    device[j].isSelect = true;
                                    devices.push(curDevice);
                                }
                            }
                        }
                    }
                    _self.device = device;
                    return {
                        autoReleaseTime: template.limited_time,
                        releaseAllowEdit: template.limited_time_allow_edit,
                        autoPassTime: template.limited_time_approve,
                        passAllowEdit: template.limited_time_approve_allow_edit,
                        autoCloseTime: template.deadline_time,
                        closeAllowEdit: template.deadline_time_allow_edit,
                        closeTimeType: 'hour',
                        devices: devices,
                        devicesAllowEdit: template.limited_os_allow_edit
                    }
                }
                $.comRequest('get','/task/project/template',{
                    tp_id: this.tpLink.id
                },function(res){
                    _self.isPageLoading = false;
                    var data = res.data;
                    var template = data.template;
                    var taskSteps = initSteps(template.custom_steps);
                    var highSet = initHighSet(template);
                    _self.highSet = highSet;
                    _self.taskSteps = taskSteps;
                },function(ero){
                    _self.isPageLoading = false;
                    $.toast(ero.message);
                });
            },
            navPreview: function () {
                var tpType = this.tpType;
                var tpLink = this.tpLink;
                if (!this.comCheckSteps()) {
                    return;
                }
                $.openUrl('common/commonTitle','push/preview',{
                    title: '预览一下',
                    taskLink: {
                        name: tpType.title + '-' + tpType.name,
                        price: tpLink.price * tpLink.num,
                        iconUrl: $.handleLocalStorage.get('pushProject') && $.handleLocalStorage.get('pushProject').platform.icon.url,
                        claim: tpLink.title,
                    },
                    taskSteps: this.taskSteps
                });
            },
            navUseTemplate: function () {
                $.openUrl('common/commonTitle','push/template',{
                    title: '可用模板',
                    tpId: this.tpLink.id,
                    tpType: this.mode === 'simple' ? 1 : 0
                });
            },
            /**
             *  获取模版
             */
            getTemplateApi: function () {
                let data = {
                    tp_id: this.tpLink.id,
                    tpl_type: this.mode === 'simple' ? 1 : 0,
                    page: 1
                };
                let _self = this;
                $.comRequest('get','/task/template/query_my_by_project',data,function(res){
                    _self.isPageLoading = false;
                    let totalRecords  = res.data.total_records;
                    if (totalRecords > 0) {
                        _self.hasTemplate = true;
                    }
                },function(ero){
                    _self.isPageLoading = false;
                    _self.hasTemplate = false;
                });
            },
            saveTaskTemplate: function () {
                if (!this.comCheckSteps()) {
                    return;
                }
                var _self = this;
                $.prompt({
                    title: '提示',
                    msg: '请输入模板昵称',
                    buttons: ['取消','确定'],
                    success:function(text){
                        if (utils.isNullStr(text)) {
                            $.toast('模版名字为空哦');
                            return;
                        }
                        var resPar = _self.parsePublishPar();
                        resPar.tpl_type = _self.mode === 'simple' ? 1 : 0;
                        resPar.tpl_name = text;
                        _self.createTemplateAPi(resPar,'创建模板成功');
                    }
                });
            },
            updateTaskTemplate: function () {
                if (!this.curTemplateLink) {
                    return;
                }
                if (!this.comCheckSteps()) {
                    return;
                }
                var curTemplateLink  = this.curTemplateLink;
                var resPar = this.parsePublishPar();
                resPar.tpl_type = this.mode === 'simple' ? 1 : 0;
                resPar.ttid = curTemplateLink.id;
                resPar.tpl_name = curTemplateLink.name;
                this.createTemplateAPi(resPar,'模板更新成功');
            },
            /**
             * 创建任务模版 api
             */
            createTemplateAPi(resPar,msg) {
                let _self = this;
                let toastMsg = msg;
                $.comRequest('post','/task/template/create',resPar,function(res){
                    $.toast(toastMsg);
                },function(ero){
                    $.toast(ero.message);
                },true);
                // this.ajax({
                //     url:'/task/template/create',
                //     method:'POST',
                //     data: resPar,
                //     load: true,
                //     success:function(res){
                //         _self.toast(toastMsg);
                //         let params = _self.getRouteParams();
                //         // 使用模版id
                //             _self.curTemplateLink = {
                //                 id: res.data.task_template_id,
                //                 name: resPar.tpl_name
                //             };
                //         _self.$refs.namePart.clearInput();
                //         _self.getTemplateApi(params.tpid,params.mode);
                //     },
                //     error: function (ero) {
                //         _self.toast(ero.message);
                //         _self.$refs.namePart.clearInput();
                //     }
                // });
            },
            useTemplate: function (template) {
                var mode = this.mode;
                var _self = this;
                var initSteps = function  (steps) {
                    var taskSteps = steps;
                    var targets = _self.targets;
                    var commands = _self.commands;
                    for(let stepIndex=0; stepIndex<taskSteps.length; stepIndex++){
                        let curStep = taskSteps[stepIndex];
                        for(let ctIndex =0; ctIndex<curStep.length; ctIndex++){
                            let curCt = curStep[ctIndex];
                            if (Array.isArray(curCt)){
                                continue;
                            }
                            curCt.canInput = true;
                            if (curCt.type === "Description" && !utils.isNullStr(curCt.value)) {
                                curCt.canInput = false;
                            }
                            if (curCt.type === "Operable") {
                                var target = {
                                    operations: []
                                };
                                var content = [];
                                for(var targetIndex=0;targetIndex<targets.length;targetIndex++) {
                                    var curTarget = targets[targetIndex];
                                    if (curTarget.name === curCt.target.type) {
                                        target = curTarget;
                                        break;
                                    }
                                }
                                for (var operIndex=0;operIndex<target.operations.length;operIndex++) {
                                    var curOper = target.operations[operIndex];
                                    if(commands[curOper]) {
                                        content.push(commands[curOper].name)
                                    }
                                }
                                curCt.target.content = content;
                                if (!utils.isNullStr(curCt.target.value)) {
                                    curCt.canInput = false;
                                }
                            }
                            if (curCt.type === "CollectTextInfo" && !utils.isNullStr(curCt.placeholder)) {
                                curCt.canInput = false;
                            }
                        }
                        taskSteps[stepIndex] = curStep;
                    }
                    return taskSteps;
                }
                var initHighSet = function (template) {
                    var device = utils.simpleCopyObj(_self.device);
                    var devices = [];
                    if (template.limited_os) {
                        for (var i=0;i<template.limited_os.systems;i++) {
                            var curDevice = template.limited_os.systems[i];
                            for (var j=0;j<device.length;j++) {
                                device[j].isSelect = false;
                                if (device[j].value === curDevice) {
                                    device[j].isSelect = true;
                                    devices.push(curDevice);
                                }
                            }
                        }
                    }
                    _self.device = device;
                    return {
                        autoReleaseTime: template.limited_time,
                        releaseAllowEdit: template.limited_time_allow_edit,
                        autoPassTime: template.limited_time_approve,
                        passAllowEdit: template.limited_time_approve_allow_edit,
                        autoCloseTime: template.deadline_time,
                        closeAllowEdit: template.deadline_time_allow_edit,
                        closeTimeType: 'hour',
                        devices: devices,
                        devicesAllowEdit: template.limited_os_allow_edit
                    }
                }
                var initSimpleTask = function (steps) {
                    var targets = _self.targets;
                    var commands = _self.commands;
                    var taskSteps = steps;
                    var cotTexts = [];
                    var simpleFlowImgs = [];
                    var simpleCheckImgs =[];
                    for(let stepIndex=0; stepIndex<taskSteps.length; stepIndex++){
                        let curStep = taskSteps[stepIndex];
                        for(let ctIndex =0; ctIndex<curStep.length; ctIndex++){
                            let curCt = curStep[ctIndex];
                            if (Array.isArray(curCt)){
                                if (stepIndex == 0) {
                                    for (var fileIndex=0;fileIndex<curCt.length;fileIndex++) {
                                        if(curCt[fileIndex].type === 'Gallery') {
                                            simpleFlowImgs.push({
                                                fid: curCt[fileIndex].fid,
                                                uri: curCt[fileIndex].uri
                                            });
                                        }
                                    }
                                    continue;
                                }
                                if(stepIndex == 1) {
                                    for (var fileIndex=0;fileIndex<curCt.length;fileIndex++) {
                                        if(curCt[fileIndex].type === 'Gallery') {
                                            simpleCheckImgs.push({
                                                fid: curCt[fileIndex].fid,
                                                uri: curCt[fileIndex].uri
                                            });
                                        }
                                    }
                                    continue;
                                }
                            }
                            if (curCt.type === "Description") {
                                _self.simpleObj.taskSpec = curCt.value;
                            }
                            if (curCt.type === "Operable") {
                                var target = {
                                    operations: []
                                };
                                var content = [];
                                for(var targetIndex=0;targetIndex<targets.length;targetIndex++) {
                                    var curTarget = targets[targetIndex];
                                    if (curTarget.name === curCt.target.type) {
                                        target = curTarget;
                                        break;
                                    }
                                }
                                for (var operIndex=0;operIndex<target.operations.length;operIndex++) {
                                    var curOper = target.operations[operIndex];
                                    if(commands[curOper]) {
                                        content.push(commands[curOper].name)
                                    }
                                }
                                curCt.target.content = content;
                                _self.simpleObj.target = {
                                    id: '',
                                    type: curCt.target.type,
                                    value: curCt.target.value,
                                    content: content
                                };
                            }
                            if (curCt.type === "CollectTextInfo") {
                                cotTexts.push(curCt.placeholder);
                            }
                        }
                    }
                    if (cotTexts.length > 0) {
                        _self.simpleObj.simpleCotTexs = cotTexts.join('\n');
                    }
                    if (simpleFlowImgs.length > 0) {
                        _self.simpleObj.simpleFlowImgs = simpleFlowImgs;
                    }
                    if (simpleCheckImgs.length > 0) {
                        _self.simpleObj.simpleCheckImgs = simpleCheckImgs;
                    }
                }
                var highSet = initHighSet(template);
                var steps = [];
                this.curTemplateLink = {
                    id: template.id,
                    name: template.name
                };
                this.highSet = highSet;
                // 模式 major 自定义 simple 简单  system 系统
                if ( mode === 'major') {
                    this.taskSteps  = [];
                    steps = initSteps(template.custom_steps);
                    this.taskSteps = steps;
                }
                if (mode === 'simple') {
                    this.simpleObj =  {
                        // 任务描述
                        taskSpec: '',
                        // 简单流程示例图集合
                        simpleFlowImgs: [],
                        // 简单流程任务参数
                        target: {
                            id: '',
                            type: '链接',
                            value: '',
                            content: ''
                        },
                        // 验收示例图集合
                        simpleCheckImgs: [],
                        // 收集文字集合
                        simpleCotTexs: '',
                    };
                    initSimpleTask(template.custom_steps);
                }
            }
        },
    });

     // 更新任务数量
    api.addEventListener({name: 'userTemplate'}, function(ret, err){
        if (ret.value) {
            app.useTemplate(ret.value);
        }
    });

}
